package services;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Category;
import model.Item;
import model.Member;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import utils.WebUtils;
import core.Lookup;
import core.ManagerLocal;
import core.MemberManagerLocal;

public class ListItem extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		
		process(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		process(req,resp);
	}

	private void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		String memberCellphone = WebUtils.safeGetParameterString(req, "memberCellphone");
		String memberEmail = WebUtils.safeGetParameterString(req, "memberEmail");
		String memberPassword = WebUtils.safeGetParameterString(req, "memberPassword");
		
		Integer idCategory = WebUtils.safeGetParameterInteger(req, "idCategory");
		
		ManagerLocal manager = Lookup.lookupManager();
		MemberManagerLocal memberManager = Lookup.lookupMemberManager();
		
		Member member = memberManager.loginMember(memberCellphone, memberEmail, memberPassword);
		
		if(member == null){
			resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "not authorized");
			return;	
		}
		
		List<Item> items = manager.listItems(member, idCategory);

		try {
			JSONObject jsonObj = new JSONObject();
			JSONArray jsonArray = new JSONArray();
			
			for (Item item : items) {
				jsonArray.put(toJson(item));
			}
			
			jsonObj.put("items", jsonArray);
			jsonObj.put("success", true);
			String outputString = jsonObj.toString();
			
			PrintWriter writer = resp.getWriter();
			resp.setContentType("text/html;charset=UTF-8");
			writer.print(outputString);
			writer.close();
		
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
		
	}

	private JSONObject toJson(Item item) throws JSONException {
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("idItem", item.getIdItem());
		jsonObj.put("name", item.getName());
		jsonObj.put("description", item.getDescription());
		
//		if(item.getCategory() != null){
//			jsonObj.put("idCategory", item.getCategory().getIdCategory());
//			jsonObj.put("categoryName", item.getCategory().getName());
//		}

		if(item.getCategories() != null){
			String categoriesName = "";
			String categoriesId = "";
			for (Category category : item.getCategories()) {
				categoriesName += category.getName() + ", ";
				categoriesId += category.getIdCategory() + ", ";
			}
			int i = categoriesName.lastIndexOf(", ");
			if(i>0){
				categoriesName = categoriesName.substring(0, i);
			}
			i = categoriesId.lastIndexOf(", ");
			if(i>0){
				categoriesId = categoriesId.substring(0, i);
			}			
			jsonObj.put("categoriesName", categoriesName);
			jsonObj.put("categoriesId", categoriesId);				
		}			
		
		jsonObj.put("latitude", item.getLatitude());
		jsonObj.put("longitude", item.getLongitude());
		jsonObj.put("street", item.getStreet());
		jsonObj.put("state", item.getState());
		jsonObj.put("city", item.getCity());
		jsonObj.put("country", item.getCountry());
		jsonObj.put("zipcode", item.getZipcode());
		
		jsonObj.put("phone", item.getPhone());
		jsonObj.put("cellphone", item.getCellphone());
		jsonObj.put("email", item.getEmail());
		jsonObj.put("skype", item.getSkype());
		jsonObj.put("url", item.getUrl());
		
		return jsonObj;
	}
}
